#coding:utf-8
from Custapp import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
import Image
import os
import time
import urllib2
import uuid
import json
def __myuploadfile(fileObj, source_pictitle, source_filename,fileorpic='pic'):
    """ 一个公用的上传文件的处理 """
    myresponse=""
    st = ""
    if fileObj:
        filename = fileObj.name.decode('utf-8', 'ignore')
        fileExt = filename.split('.')[1]
        file_name = str(uuid.uuid1())
        subfolder = time.strftime("%Y%m")
        if not os.path.exists(settings.MEDIA_ROOT[0] + subfolder):
            os.makedirs(settings.MEDIA_ROOT[0] + subfolder)
        path = str(subfolder + '/' + file_name + '.' + fileExt)
        
        if fileExt.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png',"rar" ,"doc" ,"docx","zip","pdf","txt","swf","wmv"):
        
            phisypath = settings.MEDIA_ROOT[0] + path
            destination = open(phisypath, 'wb+')
            for chunk in fileObj.chunks():
                destination.write(chunk)            
            destination.close()
            
            if fileorpic=='pic':
                if fileExt.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png'):
                    im = Image.open(phisypath)
                    im.thumbnail((720, 720))
                    im.save(phisypath)
                    
            real_url = '/Static/images/' + subfolder + '/' + file_name + '.' + fileExt      
            st = "{'state':'SUCCESS','url':"+real_url+",'titlt':"+source_pictitle+",'original':"+source_filename+",'type':'jpg','size':'1024'}"
            st=json.loads(st)
            myresponse = "{'original':'%s','url':'%s','title':'%s','state':'%s','error':'%s'}" % (source_filename, real_url, source_pictitle, 'SUCCESS','null')
    return st


@csrf_exempt
def ueditor_ImgUp(request): 
    """ 上传图片 """   
    fileObj = request.FILES.get('upfile', None)   
    source_pictitle = request.POST.get('pictitle','')
    source_filename = request.POST.get('fileName','')  
    response = HttpResponse()  
    myresponse = __myuploadfile(fileObj, source_pictitle, source_filename,'pic')
    response.write(myresponse)
    return response
   
    
@csrf_exempt
def ueditor_FileUp(request): 
    """ 上传文件 """   
    fileObj = request.FILES.get('upfile', None)   
    source_pictitle = request.POST.get('pictitle','')
    source_filename = request.POST.get('fileName','')    
    response = HttpResponse()  
    myresponse = __myuploadfile(fileObj, source_pictitle, source_filename,'file')
    response.write(myresponse)
    return response

